# main.py
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
from datetime import datetime
from typing import List, Optional
from fastapi.middleware.cors import CORSMiddleware
import os
import logging
from TourismRecommender import TourismRecommender  # 修正导入方式
import travel_guide03211828 as travel_guide

# 初始化FastAPI应用
app = FastAPI()

# 初始化推荐系统
recommender = TourismRecommender()

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)


# ==== 数据模型定义 ====
class RecommendationRequest(BaseModel):
    age: int = Field(..., example=30)
    interests: str = Field(..., example="history, culture")
    preferred_tour_duration: int = Field(
        ...,
        alias="preferredTourDuration",
        example=5
    )
    sites_visited: List[str] = Field(
        ...,
        alias="sitesVisited",
        example=[]
    )


class BaseInfo(BaseModel):
    destination: str
    departure_date: datetime
    duration: str
    group_description: str


class Preferences(BaseModel):
    style: str
    restrictions: Optional[str] = None


class Resources(BaseModel):
    budget: str
    accommodation: str
    transportation: str


class TravelGuideRequest(BaseModel):
    base_info: BaseInfo
    preferences: Preferences
    resources: Resources
    selected_interests: List[str]
    existing_interests: Optional[List[str]] = None


# ==== 路由端点 ====
@app.post("/recommend")
async def get_recommendations(request: RecommendationRequest):
    try:
        # 使用Pydantic模型的dict方法
        user_data = request.model_dump(by_alias=True)

        # 清洗输入数据
        clean_sites = [s.strip(' "\'[]') for s in user_data['sitesVisited']]

        recommendations = recommender.get_recommendations({
            "age": user_data['age'],
            "interests": user_data['interests'],
            "preferred_tour_duration": user_data['preferredTourDuration'],
            "sites_visited": clean_sites
        })

        return {
            "recommendations": [
                {"site": site, "score": round(score, 2)}
                for site, score in recommendations
            ]
        }
    except Exception as e:
        logger.error(f"Recommendation error: {str(e)}")
        raise HTTPException(500, detail=str(e))


@app.post("/generate-guide")
async def generate_guide(request: TravelGuideRequest):
    try:
        api_key = os.getenv("DASHSCOPE_API_KEY")
        if not api_key:
            raise HTTPException(500, detail="API key missing")

        # 转换Pydantic模型为字典
        request_data = request.model_dump()

        guide = travel_guide.generate_travel_guide(
            api_key=api_key,
            request_data=request_data
        )

        return {"guide": guide} if guide else HTTPException(500, "Generation failed")

    except Exception as e:
        logger.error(f"Guide generation error: {str(e)}")
        raise HTTPException(500, detail=str(e))


# ==== 运行服务 ====
if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="127.0.0.1", port=8000)